"""
策略管理页面
提供策略创建、编辑、回测、部署等功能
"""

import streamlit as st
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json
from typing import Dict, List, Any, Optional

from ..services.data_service import get_data_service
from ..components.common import (
    create_sidebar_navigation, make_api_request,
    display_loading_spinner, show_success_message, show_error_message
)
from ..components.metrics import create_metric_card, create_status_indicator
from ..components.charts import create_line_chart, create_bar_chart, create_candlestick_chart
from ..components.tables import create_data_table, create_editable_table
from ..components.filters import create_date_filter, create_multiselect_filter


# 数据获取函数
@st.cache_data(ttl=300)
def get_strategy_overview():
    """获取策略概览数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("strategy_overview")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取策略概览数据失败: {e}")
    
    # 降级数据
    return {
        "total_strategies": {"value": "25", "delta": "3"},
        "running_strategies": {"value": "8", "delta": "2"},
        "paused_strategies": {"value": "5", "delta": "-1"},
        "stopped_strategies": {"value": "12", "delta": "2"}
    }

@st.cache_data(ttl=300)
def get_strategy_list():
    """获取策略列表数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("strategy_list")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取策略列表数据失败: {e}")
    
    # 降级数据
    return pd.DataFrame({
        '策略名称': ['均线策略', '动量策略', '均值回归', '网格交易', '套利策略', '趋势跟踪'],
        '策略类型': ['技术分析', '量化因子', '统计套利', '网格交易', '套利', '趋势'],
        '状态': ['运行中', '运行中', '暂停', '运行中', '停止', '运行中'],
        '创建时间': ['2024-01-10', '2024-01-12', '2024-01-08', '2024-01-15', '2024-01-05', '2024-01-13'],
        '最后修改': ['2024-01-15', '2024-01-14', '2024-01-10', '2024-01-15', '2024-01-06', '2024-01-14'],
        '年化收益': ['15.2%', '22.8%', '8.5%', '12.3%', '6.7%', '18.9%'],
        '最大回撤': ['-8.5%', '-12.3%', '-5.2%', '-6.8%', '-3.1%', '-9.7%'],
        '夏普比率': ['1.85', '2.12', '1.23', '1.67', '1.45', '1.98']
    })

@st.cache_data(ttl=300)
def get_strategy_performance_comparison(selected_strategies):
    """获取策略性能对比数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("strategy_performance", {"strategies": selected_strategies})
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取策略性能对比数据失败: {e}")
    
    # 降级数据
    return pd.DataFrame({
        '策略': selected_strategies,
        '年化收益': [15.2, 22.8, 18.9][:len(selected_strategies)],
        '最大回撤': [8.5, 12.3, 9.7][:len(selected_strategies)],
        '夏普比率': [1.85, 2.12, 1.98][:len(selected_strategies)],
        '胜率': [65.2, 58.7, 62.3][:len(selected_strategies)]
    })

@st.cache_data(ttl=300)
def get_backtest_results():
    """获取回测结果数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("backtest_results")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取回测结果数据失败: {e}")
    
    # 降级数据
    return {
        "total_return": {"value": "25.8%", "delta": "15.8%"},
        "annual_return": {"value": "18.2%", "delta": "8.2%"},
        "max_drawdown": {"value": "-8.5%", "delta": "-3.5%"},
        "sharpe_ratio": {"value": "1.85", "delta": "0.85"}
    }

@st.cache_data(ttl=300)
def get_nav_curve_data():
    """获取净值曲线数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("nav_curve")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取净值曲线数据失败: {e}")
    
    # 降级数据
    dates = pd.date_range(start='2023-01-01', end='2024-01-01', freq='D')
    return pd.DataFrame({
        '日期': dates,
        '策略净值': [1.0 + i * 0.001 + np.random.normal(0, 0.01) for i in range(len(dates))],
        '基准净值': [1.0 + i * 0.0005 + np.random.normal(0, 0.008) for i in range(len(dates))]
    })

@st.cache_data(ttl=300)
def get_returns_stats():
    """获取收益统计数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("returns_stats")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取收益统计数据失败: {e}")
    
    # 降级数据
    return pd.DataFrame({
        '指标': ['总收益率', '年化收益率', '月度胜率', '最大单日收益', '最大单日亏损'],
        '策略': ['25.8%', '18.2%', '65.2%', '3.2%', '-2.8%'],
        '基准': ['12.5%', '10.1%', '58.7%', '2.1%', '-3.5%']
    })

@st.cache_data(ttl=300)
def get_risk_stats():
    """获取风险统计数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("risk_stats")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取风险统计数据失败: {e}")
    
    # 降级数据
    return pd.DataFrame({
        '指标': ['最大回撤', '波动率', '夏普比率', 'VaR(95%)', '卡玛比率'],
        '策略': ['-8.5%', '15.2%', '1.85', '-2.1%', '2.14'],
        '基准': ['-12.3%', '18.7%', '1.23', '-2.8%', '1.67']
    })

@st.cache_data(ttl=300)
def get_trade_records():
    """获取交易记录数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("trade_records")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取交易记录数据失败: {e}")
    
    # 降级数据
    return pd.DataFrame({
        '时间': ['2023-06-15', '2023-06-20', '2023-07-02', '2023-07-10'],
        '股票': ['000001.SZ', '000002.SZ', '600000.SH', '000001.SZ'],
        '操作': ['买入', '卖出', '买入', '卖出'],
        '价格': [12.50, 18.30, 8.90, 13.20],
        '数量': [1000, 800, 1200, 1000],
        '金额': [12500, 14640, 10680, 13200],
        '收益': [0, 4640, 0, 700],
        '收益率': ['0%', '31.8%', '0%', '5.6%']
    })

@st.cache_data(ttl=300)
def get_deployment_overview():
    """获取部署状态概览数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("deployment_overview")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取部署状态概览数据失败: {e}")
    
    # 降级数据
    return {
        "running_strategies": {"value": "8", "delta": "2"},
        "today_trades": {"value": "25", "delta": "8"},
        "total_pnl": {"value": "+12.5%", "delta": "2.3%"},
        "available_funds": {"value": "85.2万", "delta": "5.2万"}
    }

@st.cache_data(ttl=300)
def get_monitoring_overview():
    """获取实时监控概览数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("monitoring_overview")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取实时监控概览数据失败: {e}")
    
    # 降级数据
    return {
        "running_strategies": {"value": "8", "delta": "0"},
        "today_signals": {"value": "15", "delta": "5"},
        "executed_orders": {"value": "12", "delta": "3"},
        "alerts": {"value": "2", "delta": "1"}
    }

@st.cache_data(ttl=300)
def get_strategy_status():
    """获取策略运行状态数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("strategy_status")
        if result and result.get("success"):
            return pd.DataFrame(result.get("data", []))
    except Exception as e:
        st.error(f"获取策略运行状态数据失败: {e}")
    
    # 降级数据
    return pd.DataFrame({
        '策略名称': ['均线策略', '动量策略', '网格交易', '套利策略', '趋势跟踪'],
        '状态': ['运行中', '运行中', '运行中', '暂停', '运行中'],
        '最后信号': ['买入', '卖出', '网格买入', '-', '持有'],
        '信号时间': ['10:30:15', '10:28:42', '10:31:05', '-', '09:45:20'],
        '当前持仓': ['1000股', '0股', '5档网格', '0股', '800股'],
        '今日盈亏': ['+2.3%', '-0.8%', '+1.2%', '0%', '+3.1%'],
        '运行时长': ['2小时30分', '2小时28分', '2小时31分', '暂停', '2小时45分']
    })

@st.cache_data(ttl=300)
def get_realtime_performance_data():
    """获取实时性能数据"""
    try:
        data_service = get_data_service()
        result = data_service.get_data_management_data("realtime_performance")
        if result and result.get("success"):
            return result.get("data", {})
    except Exception as e:
        st.error(f"获取实时性能数据失败: {e}")
    
    # 降级数据
    time_data = pd.DataFrame({
        '时间': pd.date_range(start='09:30', end='11:30', freq='5min'),
        '累计收益': [i * 0.1 + np.random.normal(0, 0.5) for i in range(25)]
    })
    
    strategy_returns = pd.DataFrame({
        '策略': ['均线策略', '动量策略', '网格交易', '趋势跟踪'],
        '今日收益': [2.3, -0.8, 1.2, 3.1]
    })
    
    return {
        "time_data": time_data,
        "strategy_returns": strategy_returns
    }


def render_strategy_management_page():
    """渲染策略管理页面"""
    st.title("🧠 策略管理")
    
    # 侧边栏导航
    create_sidebar_navigation()
    
    # 创建标签页
    tab1, tab2, tab3, tab4, tab5 = st.tabs([
        "策略列表", "策略编辑器", "回测分析", "实盘部署", "策略监控"
    ])
    
    with tab1:
        render_strategy_list_tab()
    
    with tab2:
        render_strategy_editor_tab()
    
    with tab3:
        render_backtest_tab()
    
    with tab4:
        render_deployment_tab()
    
    with tab5:
        render_monitoring_tab()


def render_strategy_list_tab():
    """渲染策略列表标签页"""
    st.header("策略列表")
    
    # 策略概览
    col1, col2, col3, col4 = st.columns(4)
    
    # 获取策略概览数据
    with st.spinner("加载策略概览..."):
        overview_data = get_strategy_overview()
    
    with col1:
        create_metric_card(
            "总策略数",
            overview_data.get("total_strategies", {}).get("value", "25"),
            "📊",
            delta=overview_data.get("total_strategies", {}).get("delta", "3"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "运行中",
            overview_data.get("running_strategies", {}).get("value", "8"),
            "🟢",
            delta=overview_data.get("running_strategies", {}).get("delta", "2"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "暂停中",
            overview_data.get("paused_strategies", {}).get("value", "5"),
            "🟡",
            delta=overview_data.get("paused_strategies", {}).get("delta", "-1"),
            delta_color="inverse"
        )
    
    with col4:
        create_metric_card(
            "已停止",
            overview_data.get("stopped_strategies", {}).get("value", "12"),
            "🔴",
            delta=overview_data.get("stopped_strategies", {}).get("delta", "2"),
            delta_color="normal"
        )
    
    st.divider()
    
    # 策略列表
    st.subheader("策略列表")
    
    # 获取策略列表数据
    with st.spinner("加载策略列表..."):
        strategies = get_strategy_list()
    
    # 过滤器
    col1, col2, col3 = st.columns(3)
    
    with col1:
        status_filter = create_multiselect_filter(
            strategies, '状态', '筛选状态', key='strategy_status'
        )
    
    with col2:
        type_filter = create_multiselect_filter(
            strategies, '策略类型', '筛选类型', key='strategy_type'
        )
    
    with col3:
        date_range = create_date_filter("创建日期范围", key='strategy_date')
    
    # 应用过滤器
    filtered_strategies = strategies.copy()
    if status_filter:
        filtered_strategies = filtered_strategies[filtered_strategies['状态'].isin(status_filter)]
    if type_filter:
        filtered_strategies = filtered_strategies[filtered_strategies['策略类型'].isin(type_filter)]
    
    # 显示策略表格
    create_data_table(filtered_strategies, "策略详情")
    
    # 策略操作
    st.subheader("策略操作")
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        if st.button("➕ 新建策略", use_container_width=True):
            st.session_state.show_new_strategy = True
    
    with col2:
        if st.button("📊 批量回测", use_container_width=True):
            st.session_state.show_batch_backtest = True
    
    with col3:
        if st.button("🚀 批量部署", use_container_width=True):
            st.session_state.show_batch_deploy = True
    
    with col4:
        if st.button("📈 性能对比", use_container_width=True):
            st.session_state.show_performance_comparison = True
    
    # 新建策略对话框
    if st.session_state.get('show_new_strategy', False):
        render_new_strategy_dialog()
    
    # 性能对比
    if st.session_state.get('show_performance_comparison', False):
        render_performance_comparison()


def render_new_strategy_dialog():
    """渲染新建策略对话框"""
    with st.expander("新建策略", expanded=True):
        col1, col2 = st.columns(2)
        
        with col1:
            strategy_name = st.text_input("策略名称")
            strategy_type = st.selectbox("策略类型", [
                "技术分析", "量化因子", "统计套利", "网格交易", "套利", "趋势", "机器学习"
            ])
            description = st.text_area("策略描述")
        
        with col2:
            template = st.selectbox("策略模板", [
                "空白策略", "均线策略", "动量策略", "均值回归", "网格交易", "自定义"
            ])
            risk_level = st.selectbox("风险等级", ["低", "中", "高"])
            initial_capital = st.number_input("初始资金", min_value=10000, value=100000)
        
        # 策略参数配置
        st.subheader("策略参数")
        
        if template == "均线策略":
            col1, col2 = st.columns(2)
            with col1:
                short_period = st.number_input("短期均线", min_value=1, max_value=100, value=5)
                long_period = st.number_input("长期均线", min_value=1, max_value=200, value=20)
            with col2:
                stop_loss = st.number_input("止损比例(%)", min_value=0.1, max_value=20.0, value=5.0)
                take_profit = st.number_input("止盈比例(%)", min_value=0.1, max_value=50.0, value=10.0)
        
        elif template == "网格交易":
            col1, col2 = st.columns(2)
            with col1:
                grid_count = st.number_input("网格数量", min_value=5, max_value=50, value=10)
                grid_spacing = st.number_input("网格间距(%)", min_value=0.1, max_value=10.0, value=2.0)
            with col2:
                base_amount = st.number_input("基础下单量", min_value=100, value=1000)
                max_position = st.number_input("最大持仓", min_value=1000, value=10000)
        
        # 操作按钮
        col1, col2, col3 = st.columns(3)
        
        with col1:
            if st.button("保存策略"):
                if strategy_name:
                    show_success_message(f"策略 '{strategy_name}' 创建成功")
                    st.session_state.show_new_strategy = False
                    st.rerun()
                else:
                    show_error_message("请输入策略名称")
        
        with col2:
            if st.button("保存并回测"):
                if strategy_name:
                    show_success_message(f"策略 '{strategy_name}' 创建成功，开始回测")
                    st.session_state.show_new_strategy = False
                    st.session_state.active_tab = "回测分析"
                    st.rerun()
                else:
                    show_error_message("请输入策略名称")
        
        with col3:
            if st.button("取消"):
                st.session_state.show_new_strategy = False
                st.rerun()


def render_performance_comparison():
    """渲染性能对比"""
    with st.expander("策略性能对比", expanded=True):
        # 选择对比策略
        selected_strategies = st.multiselect(
            "选择要对比的策略",
            ["均线策略", "动量策略", "均值回归", "网格交易", "套利策略", "趋势跟踪"],
            default=["均线策略", "动量策略", "趋势跟踪"]
        )
        
        if selected_strategies:
            # 获取性能对比数据
            with st.spinner("加载性能对比数据..."):
                performance_data = get_strategy_performance_comparison(selected_strategies)
            
            # 性能对比图表
            col1, col2 = st.columns(2)
            
            with col1:
                create_bar_chart(
                    performance_data,
                    x_col='策略',
                    y_col='年化收益',
                    title="年化收益对比"
                )
            
            with col2:
                create_bar_chart(
                    performance_data,
                    x_col='策略',
                    y_col='夏普比率',
                    title="夏普比率对比"
                )
            
            # 详细对比表
            st.subheader("详细对比")
            create_data_table(performance_data, "策略性能对比")
        
        if st.button("关闭对比"):
            st.session_state.show_performance_comparison = False
            st.rerun()


def render_strategy_editor_tab():
    """渲染策略编辑器标签页"""
    st.header("策略编辑器")
    
    # 策略选择
    col1, col2 = st.columns([2, 1])
    
    with col1:
        selected_strategy = st.selectbox(
            "选择要编辑的策略",
            ["新建策略", "均线策略", "动量策略", "均值回归", "网格交易"]
        )
    
    with col2:
        editor_mode = st.selectbox("编辑模式", ["可视化编辑", "代码编辑"])
    
    if editor_mode == "可视化编辑":
        render_visual_editor()
    else:
        render_code_editor()


def render_visual_editor():
    """渲染可视化编辑器"""
    st.subheader("可视化策略编辑器")
    
    # 策略基本信息
    with st.expander("基本信息", expanded=True):
        col1, col2 = st.columns(2)
        
        with col1:
            strategy_name = st.text_input("策略名称", value="均线策略")
            strategy_desc = st.text_area("策略描述", value="基于移动平均线的交易策略")
        
        with col2:
            risk_level = st.selectbox("风险等级", ["低", "中", "高"], index=1)
            max_positions = st.number_input("最大持仓数", min_value=1, max_value=50, value=10)
    
    # 信号配置
    with st.expander("交易信号配置", expanded=True):
        st.subheader("买入信号")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            buy_indicator1 = st.selectbox("指标1", ["MA", "EMA", "RSI", "MACD", "KDJ"])
            buy_period1 = st.number_input("周期1", min_value=1, max_value=200, value=5)
        
        with col2:
            buy_operator = st.selectbox("操作符", [">", "<", ">=", "<=", "="])
            buy_indicator2 = st.selectbox("指标2", ["MA", "EMA", "RSI", "MACD", "价格"])
            buy_period2 = st.number_input("周期2", min_value=1, max_value=200, value=20)
        
        with col3:
            buy_threshold = st.number_input("阈值", value=0.0)
            buy_volume_filter = st.checkbox("成交量过滤")
        
        st.subheader("卖出信号")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            sell_indicator1 = st.selectbox("指标1 ", ["MA", "EMA", "RSI", "MACD", "KDJ"])
            sell_period1 = st.number_input("周期1 ", min_value=1, max_value=200, value=5)
        
        with col2:
            sell_operator = st.selectbox("操作符 ", [">", "<", ">=", "<=", "="])
            sell_indicator2 = st.selectbox("指标2 ", ["MA", "EMA", "RSI", "MACD", "价格"])
            sell_period2 = st.number_input("周期2 ", min_value=1, max_value=200, value=20)
        
        with col3:
            sell_threshold = st.number_input("阈值 ", value=0.0)
            sell_volume_filter = st.checkbox("成交量过滤 ")
    
    # 风险管理
    with st.expander("风险管理", expanded=True):
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("止损设置")
            enable_stop_loss = st.checkbox("启用止损", value=True)
            if enable_stop_loss:
                stop_loss_type = st.selectbox("止损类型", ["固定比例", "ATR", "支撑位"])
                stop_loss_value = st.number_input("止损值(%)", min_value=0.1, max_value=20.0, value=5.0)
        
        with col2:
            st.subheader("止盈设置")
            enable_take_profit = st.checkbox("启用止盈", value=True)
            if enable_take_profit:
                take_profit_type = st.selectbox("止盈类型", ["固定比例", "ATR", "阻力位"])
                take_profit_value = st.number_input("止盈值(%)", min_value=0.1, max_value=50.0, value=10.0)
    
    # 资金管理
    with st.expander("资金管理", expanded=True):
        col1, col2 = st.columns(2)
        
        with col1:
            position_sizing = st.selectbox("仓位管理", ["固定金额", "固定比例", "凯利公式", "风险平价"])
            if position_sizing == "固定金额":
                fixed_amount = st.number_input("固定金额", min_value=1000, value=10000)
            elif position_sizing == "固定比例":
                fixed_ratio = st.slider("固定比例(%)", 1, 100, 10)
        
        with col2:
            max_single_position = st.slider("单个持仓最大比例(%)", 1, 50, 20)
            max_total_position = st.slider("总持仓最大比例(%)", 50, 100, 80)
    
    # 保存按钮
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button("保存策略", use_container_width=True):
            show_success_message("策略保存成功")
    
    with col2:
        if st.button("验证策略", use_container_width=True):
            with st.spinner("验证策略中..."):
                # 模拟策略验证
                st.success("策略验证通过")
    
    with col3:
        if st.button("生成代码", use_container_width=True):
            st.session_state.show_generated_code = True


def render_code_editor():
    """渲染代码编辑器"""
    st.subheader("策略代码编辑器")
    
    # 代码模板选择
    template = st.selectbox("选择代码模板", [
        "空白模板", "均线策略模板", "动量策略模板", "网格交易模板"
    ])
    
    # 默认代码
    default_code = '''
import pandas as pd
import numpy as np
from typing import Dict, List, Any

class Strategy:
    def __init__(self, params: Dict[str, Any]):
        self.params = params
        self.positions = {}
        
    def initialize(self):
        """策略初始化"""
        pass
        
    def on_data(self, data: pd.DataFrame) -> List[Dict]:
        """处理数据并生成交易信号"""
        signals = []
        
        # 计算技术指标
        data['ma_short'] = data['close'].rolling(self.params['short_period']).mean()
        data['ma_long'] = data['close'].rolling(self.params['long_period']).mean()
        
        # 生成交易信号
        for symbol in data['symbol'].unique():
            symbol_data = data[data['symbol'] == symbol].iloc[-1]
            
            if symbol_data['ma_short'] > symbol_data['ma_long']:
                # 买入信号
                signals.append({
                    'symbol': symbol,
                    'action': 'buy',
                    'quantity': 100,
                    'price': symbol_data['close']
                })
            elif symbol_data['ma_short'] < symbol_data['ma_long']:
                # 卖出信号
                signals.append({
                    'symbol': symbol,
                    'action': 'sell',
                    'quantity': 100,
                    'price': symbol_data['close']
                })
        
        return signals
        
    def on_order_filled(self, order: Dict):
        """订单成交回调"""
        pass
        
    def on_risk_check(self) -> bool:
        """风险检查"""
        return True
'''
    
    # 代码编辑器
    code = st.text_area(
        "策略代码",
        value=default_code,
        height=400,
        help="请输入Python策略代码"
    )
    
    # 参数配置
    st.subheader("策略参数")
    
    col1, col2 = st.columns(2)
    
    with col1:
        params_json = st.text_area(
            "参数配置(JSON格式)",
            value='{\n  "short_period": 5,\n  "long_period": 20,\n  "stop_loss": 0.05\n}',
            height=150
        )
    
    with col2:
        # 参数验证
        try:
            params = json.loads(params_json)
            st.success("参数格式正确")
            st.json(params)
        except json.JSONDecodeError as e:
            st.error(f"参数格式错误: {e}")
    
    # 代码操作
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        if st.button("语法检查", use_container_width=True):
            try:
                compile(code, '<string>', 'exec')
                st.success("语法检查通过")
            except SyntaxError as e:
                st.error(f"语法错误: {e}")
    
    with col2:
        if st.button("保存代码", use_container_width=True):
            show_success_message("代码保存成功")
    
    with col3:
        if st.button("运行测试", use_container_width=True):
            with st.spinner("运行测试中..."):
                # 模拟代码测试
                st.success("测试运行成功")
    
    with col4:
        if st.button("部署策略", use_container_width=True):
            st.session_state.show_deploy_dialog = True


def render_backtest_tab():
    """渲染回测分析标签页"""
    st.header("回测分析")
    
    # 回测配置
    with st.expander("回测配置", expanded=True):
        col1, col2, col3 = st.columns(3)
        
        with col1:
            strategy_select = st.selectbox("选择策略", ["均线策略", "动量策略", "网格交易"])
            start_date, end_date = create_date_filter("回测时间范围")
        
        with col2:
            initial_capital = st.number_input("初始资金", min_value=10000, value=100000)
            commission = st.number_input("手续费率(%)", min_value=0.0, max_value=1.0, value=0.1)
        
        with col3:
            benchmark = st.selectbox("基准指数", ["沪深300", "中证500", "创业板指"])
            frequency = st.selectbox("回测频率", ["日", "小时", "分钟"])
        
        if st.button("开始回测", type="primary"):
            with st.spinner("回测运行中..."):
                # 模拟回测过程
                progress_bar = st.progress(0)
                for i in range(100):
                    progress_bar.progress(i + 1)
                
                st.session_state.backtest_completed = True
                show_success_message("回测完成")
    
    # 回测结果
    if st.session_state.get('backtest_completed', False):
        render_backtest_results()


def render_backtest_results():
    """渲染回测结果"""
    st.subheader("回测结果")
    
    # 获取回测结果关键指标
    with st.spinner("加载回测结果..."):
        backtest_data = get_backtest_results()
    
    # 关键指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "总收益率",
            backtest_data.get("total_return", {}).get("value", "25.8%"),
            "📈",
            delta=backtest_data.get("total_return", {}).get("delta", "15.8%"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "年化收益率",
            backtest_data.get("annual_return", {}).get("value", "18.2%"),
            "📊",
            delta=backtest_data.get("annual_return", {}).get("delta", "8.2%"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "最大回撤",
            backtest_data.get("max_drawdown", {}).get("value", "-8.5%"),
            "📉",
            delta=backtest_data.get("max_drawdown", {}).get("delta", "-3.5%"),
            delta_color="inverse"
        )
    
    with col4:
        create_metric_card(
            "夏普比率",
            backtest_data.get("sharpe_ratio", {}).get("value", "1.85"),
            "⭐",
            delta=backtest_data.get("sharpe_ratio", {}).get("delta", "0.85"),
            delta_color="normal"
        )
    
    # 净值曲线
    st.subheader("净值曲线")
    
    # 获取净值曲线数据
    with st.spinner("加载净值曲线..."):
        nav_data = get_nav_curve_data()
    
    create_line_chart(
        nav_data,
        x_col='日期',
        y_col='策略净值',
        title="策略净值走势",
        height=400
    )
    
    # 详细统计
    col1, col2 = st.columns(2)
    
    with col1:
        st.subheader("收益统计")
        # 获取收益统计数据
        with st.spinner("加载收益统计..."):
            returns_stats = get_returns_stats()
        create_data_table(returns_stats)
    
    with col2:
        st.subheader("风险统计")
        # 获取风险统计数据
        with st.spinner("加载风险统计..."):
            risk_stats = get_risk_stats()
        create_data_table(risk_stats)
    
    # 交易记录
    st.subheader("交易记录")
    
    # 获取交易记录数据
    with st.spinner("加载交易记录..."):
        trades = get_trade_records()
    
    create_data_table(trades, "交易明细")


def render_deployment_tab():
    """渲染实盘部署标签页"""
    st.header("实盘部署")
    
    # 部署状态概览
    st.subheader("部署状态概览")
    
    # 获取部署状态概览数据
    with st.spinner("加载部署状态..."):
        deployment_data = get_deployment_overview()
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "已部署策略",
            deployment_data.get("deployed_strategies", {}).get("value", "8"),
            "🚀",
            delta=deployment_data.get("deployed_strategies", {}).get("delta", "2"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "运行中",
            deployment_data.get("running", {}).get("value", "6"),
            "▶️",
            delta=deployment_data.get("running", {}).get("delta", "1"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "暂停中",
            deployment_data.get("paused", {}).get("value", "2"),
            "⏸️",
            delta=deployment_data.get("paused", {}).get("delta", "-1"),
            delta_color="inverse"
        )
    
    with col4:
        create_metric_card(
            "错误状态",
            deployment_data.get("error", {}).get("value", "0"),
            "❌",
            delta=deployment_data.get("error", {}).get("delta", "0"),
            delta_color="off"
        )
    
    st.divider()
    
    # 策略部署
    st.subheader("策略部署")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        deploy_strategy = st.selectbox("选择要部署的策略", ["均线策略", "动量策略", "网格交易"])
        
        # 部署配置
        with st.expander("部署配置"):
            col1, col2 = st.columns(2)
            
            with col1:
                account = st.selectbox("交易账户", ["模拟账户", "实盘账户1", "实盘账户2"])
                initial_capital = st.number_input("分配资金", min_value=10000, value=100000)
            
            with col2:
                max_positions = st.number_input("最大持仓数", min_value=1, max_value=50, value=10)
                risk_limit = st.number_input("风险限额(%)", min_value=1, max_value=50, value=20)
    
    with col2:
        st.subheader("部署操作")
        
        if st.button("🚀 部署策略", use_container_width=True):
            with st.spinner("部署中..."):
                # 模拟部署过程
                show_success_message("策略部署成功")
        
        if st.button("⏸️ 暂停策略", use_container_width=True):
            show_success_message("策略已暂停")
        
        if st.button("🛑 停止策略", use_container_width=True):
            show_success_message("策略已停止")


def render_monitoring_tab():
    """渲染策略监控标签页"""
    st.header("策略监控")
    
    # 实时监控概览
    st.subheader("实时监控概览")
    
    # 获取实时监控概览数据
    with st.spinner("加载监控概览..."):
        monitoring_data = get_monitoring_overview()
    
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        create_metric_card(
            "运行策略",
            monitoring_data.get("running_strategies", {}).get("value", "8"),
            "🟢",
            delta=monitoring_data.get("running_strategies", {}).get("delta", "0"),
            delta_color="normal"
        )
    
    with col2:
        create_metric_card(
            "今日信号",
            monitoring_data.get("today_signals", {}).get("value", "15"),
            "📡",
            delta=monitoring_data.get("today_signals", {}).get("delta", "5"),
            delta_color="normal"
        )
    
    with col3:
        create_metric_card(
            "执行订单",
            monitoring_data.get("executed_orders", {}).get("value", "12"),
            "📋",
            delta=monitoring_data.get("executed_orders", {}).get("delta", "3"),
            delta_color="normal"
        )
    
    with col4:
        create_metric_card(
            "异常告警",
            monitoring_data.get("alerts", {}).get("value", "2"),
            "⚠️",
            delta=monitoring_data.get("alerts", {}).get("delta", "1"),
            delta_color="inverse"
        )
    
    st.divider()
    
    # 策略运行状态
    st.subheader("策略运行状态")
    
    # 获取策略运行状态数据
    with st.spinner("加载策略状态..."):
        strategy_status = get_strategy_status()
    
    create_data_table(strategy_status, "策略状态监控")
    
    # 实时日志
    st.subheader("实时日志")
    
    # 日志过滤
    col1, col2, col3 = st.columns(3)
    
    with col1:
        log_level = st.selectbox("日志级别", ["全部", "INFO", "WARNING", "ERROR"])
    
    with col2:
        log_strategy = st.selectbox("策略筛选", ["全部"] + strategy_status['策略名称'].tolist())
    
    with col3:
        auto_refresh = st.checkbox("自动刷新", value=True)
    
    # 模拟日志数据
    logs = [
        {"时间": "10:31:15", "级别": "INFO", "策略": "均线策略", "消息": "生成买入信号: 000001.SZ @ 12.50"},
        {"时间": "10:31:05", "级别": "INFO", "策略": "网格交易", "消息": "网格买入执行成功: 600000.SH @ 8.90"},
        {"时间": "10:30:45", "级别": "WARNING", "策略": "动量策略", "消息": "持仓接近风险限额"},
        {"时间": "10:30:30", "级别": "ERROR", "策略": "套利策略", "消息": "价差异常，策略暂停"},
        {"时间": "10:30:15", "级别": "INFO", "策略": "趋势跟踪", "消息": "趋势确认，继续持有"}
    ]
    
    # 显示日志
    for log in logs:
        if log_level != "全部" and log["级别"] != log_level:
            continue
        if log_strategy != "全部" and log["策略"] != log_strategy:
            continue
            
        level_color = {
            "INFO": "🔵",
            "WARNING": "🟡",
            "ERROR": "🔴"
        }
        
        st.write(f"{level_color[log['级别']]} `{log['时间']}` **{log['策略']}** - {log['消息']}")
    
    # 性能监控
    st.subheader("性能监控")
    
    col1, col2 = st.columns(2)
    
    with col1:
        # 获取实时性能数据
        with st.spinner("加载实时性能..."):
            time_data = get_realtime_performance_data()
        
        create_line_chart(
            time_data,
            x_col='时间',
            y_col='累计收益',
            title="实时收益曲线",
            height=300
        )
    
    with col2:
        # 策略收益对比
        strategy_returns = pd.DataFrame({
            '策略': ['均线策略', '动量策略', '网格交易', '趋势跟踪'],
            '今日收益': [2.3, -0.8, 1.2, 3.1]
        })
        
        create_bar_chart(
            strategy_returns,
            x_col='策略',
            y_col='今日收益',
            title="策略今日收益对比",
            height=300
        )
    
    # 风险监控
    st.subheader("风险监控")
    
    # 风险指标
    risk_metrics = pd.DataFrame({
        '风险指标': ['总持仓比例', '单策略最大持仓', '日内最大回撤', '波动率', 'VaR(95%)'],
        '当前值': ['75.2%', '25.8%', '-2.1%', '18.5%', '-3.2%'],
        '风险限额': ['80%', '30%', '-5%', '25%', '-5%'],
        '状态': ['正常', '正常', '正常', '正常', '正常']
    })
    
    create_data_table(risk_metrics, "风险指标监控")
    
    # 告警设置
    with st.expander("告警设置"):
        col1, col2 = st.columns(2)
        
        with col1:
            st.subheader("收益告警")
            profit_alert = st.checkbox("启用收益告警", value=True)
            if profit_alert:
                profit_threshold = st.number_input("收益告警阈值(%)", value=5.0)
                loss_threshold = st.number_input("亏损告警阈值(%)", value=-3.0)
        
        with col2:
            st.subheader("风险告警")
            risk_alert = st.checkbox("启用风险告警", value=True)
            if risk_alert:
                position_threshold = st.slider("持仓告警阈值(%)", 50, 100, 80)
                drawdown_threshold = st.slider("回撤告警阈值(%)", 1, 20, 5)
        
        if st.button("保存告警设置"):
            show_success_message("告警设置已保存")